/**
 * 
 */
package info.noahcampbell.meter.management.plugin;

import info.noahcampbell.meter.messenger.accumulator.Accumulator;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author Noah Campbell
 * @version 1.0
 */
public class GraphHelper extends HttpServlet {

    
    
    /** The serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /**
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @SuppressWarnings("unused")
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(request.getPathInfo().endsWith("dsnames")) {
            
            List<String> names = new ArrayList<String>(); 
            OutputStream out = response.getOutputStream();
            
            String name = request.getParameter("val");
            if(name != null && name.length() > 0) {
                try {
                    names = getDatasourceNames(name);
                } catch (Exception e) {
                    // ignore
                }
            }
            
            StringBuilder builder = new StringBuilder();
            builder.append("<names>");
            for(String n : names) { 
                builder.append("<name>").append(n).append("</name>");
            }
            builder.append("</names>");
            out.write(builder.toString().getBytes());
            
        }
    }

    /**
     * @param name
     * @return listofNames
     * @throws Exception
     */
    public List<String> getDatasourceNames(String name) throws Exception {
        for(Accumulator a : RrdManager.getGraphableObjectNames()) {
            if(!a.getSourceMBean().getCanonicalName().equalsIgnoreCase(name)) continue;
            return a.getDatasourceNames();
        }
        return new ArrayList<String>();
    }
}
